import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes'
import { isAuth } from '../utils/auth'

Vue.use(VueRouter)

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

const whiteList = ['/login']

router.beforeEach((to, from, next) => {
  if (isAuth()) {
    /* has token */
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      next()
    }
  } else {
    // 没有token
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next()
    } else {
      next('/login') // 否则全部重定向到登录页
    }
  }
})

// 解决重复多次点击某个操作，频繁触发同一个路由的情况
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

export default router
